﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Furion;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using YShop.Core.System;

namespace YShop.Core
{
    public class FileManager: IScoped
    {
        private readonly IRepository<Resource> _repository;
        private readonly IConfiguration _configuration;

        public FileManager(IRepository<Resource> repository, IConfiguration configuration)
        {
            _repository = repository;
            _configuration = configuration;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public async Task DeleteFileInfo(string fileId)
        {
            var file = await _repository.FirstOrDefaultAsync(u => u.Id == fileId);
            if (file != null)
            {
                await _repository.DeleteAsync(file);

                var filePath = App.WebHostEnvironment.WebRootPath + file.Path + file.Location;
                if (File.Exists(filePath))
                    File.Delete(filePath);
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task UploadFileDefault(IFormFile file)
        {
            await UploadFile(file, _configuration["UploadFile:Default:path"]);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public async Task<IActionResult> Download(string fileId)
        {
            var file = await _repository.FindAsync(fileId);
            var filePath = App.WebHostEnvironment.WebRootPath + file.Path + file.StorageName;
            var fileName = HttpUtility.UrlEncode(file.Name, Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(new FileStream(filePath, FileMode.Open), "application/octet-stream") { FileDownloadName = fileName };
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="directory"></param>
        /// <returns></returns>
        public async Task<Resource> UploadFile(IFormFile file, string directory = null)
        {
            if (string.IsNullOrEmpty(directory))
                directory = "other";

            var fileId = Utils.NewGuid().Replace("-", "");

            var fileSizeKb = (long)(file.Length / 1024.0); // 文件大小KB
            var finalName = file.FileName; // 文件原始名称
            var fileSuffix = Path.GetExtension(file.FileName).ToLower(); // 文件后缀
            var localName = $"{fileId}{fileSuffix}";

            var filePath = Path.Combine("wwwroot", $"{directory}\\");
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            using (var stream = File.Create(filePath + localName))
            {
                await file.CopyToAsync(stream);
            }

            var resource = new Resource
            {
                Id = fileId,
                Location = (int)FileLocation.Local,
                Path = $"/{directory}",
                StorageName = localName,
                Name = finalName,
                Extension = fileSuffix.TrimStart('.'),
                Size = fileSizeKb
            };
            var res = await _repository.InsertAsync(resource);
            return res.Entity;
        }
    }
}
